package main

import (
	"github.com/spf13/viper"
	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common"
	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/profile"
	dnspod "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/dnspod/v20210323"
	ssl "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/ssl/v20191205"
)

var sslClient *ssl.Client
var dnsClient *dnspod.Client

func InitTencentApi() {
	credential := common.NewCredential(
		viper.GetString("secretId"),
		viper.GetString("secretKey"),
	)
	cpf := profile.NewClientProfile()
	cpf.HttpProfile.Endpoint = viper.GetString("endpoint.ssl")
	sslClient, _ = ssl.NewClient(credential, "", cpf)

	cpf = profile.NewClientProfile()
	cpf.HttpProfile.Endpoint = viper.GetString("endpoint.dns")
	dnsClient, _ = dnspod.NewClient(credential, "", cpf)
}

func ListCertificates() (*ssl.DescribeCertificatesResponse, error) {
	logger.Println("查询服务器证书列表...")
	// 实例化一个请求对象,每个接口都会对应一个request对象
	request := ssl.NewDescribeCertificatesRequest()

	request.Limit = common.Uint64Ptr(50)
	request.ExpirationSort = common.StringPtr("ASC")

	return sslClient.DescribeCertificates(request)
}

func ApplyCertificate(domain, email, alias string) (*ssl.ApplyCertificateResponse, error) {
	// 实例化一个请求对象,每个接口都会对应一个request对象
	request := ssl.NewApplyCertificateRequest()

	request.DvAuthMethod = common.StringPtr("DNS_AUTO")
	request.DomainName = common.StringPtr(domain)
	request.ContactEmail = common.StringPtr(email)
	request.CsrEncryptAlgo = common.StringPtr("RSA")
	request.CsrKeyPassword = common.StringPtr("Qwer.1234//")
	request.Alias = common.StringPtr(alias)
	request.DeleteDnsAutoRecord = common.BoolPtr(true)

	// 返回的resp是一个ApplyCertificateResponse的实例，与请求对象对应
	return sslClient.ApplyCertificate(request)
}

func CompleteCertificate(certificateId string) (*ssl.CompleteCertificateResponse, error) {
	request := ssl.NewCompleteCertificateRequest()
	request.CertificateId = common.StringPtr(certificateId)
	return sslClient.CompleteCertificate(request)
}

func DescribeCertificate(certificateId string) (*ssl.DescribeCertificateResponse, error) {
	request := ssl.NewDescribeCertificateRequest()
	request.CertificateId = common.StringPtr(certificateId)
	return sslClient.DescribeCertificate(request)
}

func DownloadCertificate(certificateId string) (*ssl.DownloadCertificateResponse, error) {
	request := ssl.NewDownloadCertificateRequest()
	request.CertificateId = common.StringPtr(certificateId)
	return sslClient.DownloadCertificate(request)
}

func DescribeDomainList() (*dnspod.DescribeDomainListResponse, error) {
	logger.Println("查询名下域名列表...")
	request := dnspod.NewDescribeDomainListRequest()
	return dnsClient.DescribeDomainList(request)
}
